package xy.come.juhenews.Activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import xy.come.juhenews.Adapter.WeatherDayAdapter;
import xy.come.juhenews.Base.BaseActivity;
import xy.come.juhenews.Bean.WeatherDayBean;
import xy.come.juhenews.Bean.WeatherLifeBean;
import xy.come.juhenews.Bean.WeatherNowBean;
import xy.come.juhenews.Bean.WeatherSunupBean;
import xy.come.juhenews.Http.Constant;
import xy.come.juhenews.R;
import xy.come.juhenews.Uitils.DataString;
import xy.come.juhenews.Uitils.LoadingDialog;
import xy.come.juhenews.Uitils.LogUtils;
import xy.come.juhenews.Uitils.SPUtils;
import xy.come.juhenews.Widget.RecyclerViewX;
import xy.come.juhenews.Widget.SunView;

/**
 * Created by Xia_焱 on 2018/8/27.
 * e-mail：XiahaotianV@163.com
 */

public class WeatherActivity extends BaseActivity {

    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_select_address)
    AutoLinearLayout llSelectAddress;
    @BindView(R.id.tv_temperature)
    TextView tvTemperature;
    @BindView(R.id.tv_context)
    TextView tvContext;
    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.ll_bg)
    AutoRelativeLayout llBg;
    @BindView(R.id.rc_list)
    RecyclerViewX rcList;
    @BindView(R.id.sv)
    SunView sv;
    @BindView(R.id.tv_wind)
    TextView tvWind;
    @BindView(R.id.tv_grade)
    TextView tvGrade;
    @BindView(R.id.tv_humidity)
    TextView tvHumidity;
    @BindView(R.id.tv_temperature_x)
    TextView tvTemperatureX;
    @BindView(R.id.tv_air)
    TextView tvAir;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.tv_life_num)
    TextView tvLifeNum;
    @BindView(R.id.tv_life_context)
    TextView tvLifeContext;
    private LoadingDialog loadingDialog;
    private String address = "沈阳";
    private String addressX = "";
    private List<WeatherDayBean.HeWeather6Bean.DailyForecastBean> list;

    @Override
    public int getLayoutId() {
        return R.layout.activity_weather;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        tvData.setText(DataString.StringData());
        loadingDialog = new LoadingDialog(WeatherActivity.this);
        rcList.setLayoutManager(new LinearLayoutManager(this));
        list = new ArrayList<>();
    }


    @Override
    protected void initData() {
        String city = (String) SPUtils.get(WeatherActivity.this, SPUtils.CITY, "");
        if (!city.equals("")) {
            address = city;
            addressX = city;
        }
        tvAddress.setText(address);
        GetNowWeather();
        GetThreeDayWeather();
        GetSunupEnd();
    }


    private void CityList() {
        final String province = (String) SPUtils.get(WeatherActivity.this, SPUtils.PROVINCE, "");
        final String code = (String) SPUtils.get(WeatherActivity.this, SPUtils.CODE, "");
        int anim = R.style.DefaultCityPickerAnimation;
        List<HotCity> hotCities = new ArrayList<>();
        hotCities.add(new HotCity("北京", "北京", "101010100"));
        hotCities.add(new HotCity("上海", "上海", "101020100"));
        hotCities.add(new HotCity("广州", "广东", "101280101"));
        hotCities.add(new HotCity("深圳", "广东", "101280601"));
        hotCities.add(new HotCity("杭州", "浙江", "101210101"));
        CityPicker.getInstance()
                .setFragmentManager(getSupportFragmentManager())    //此方法必须调用
                .enableAnimation(true)    //启用动画效果
                .setAnimationStyle(anim)    //自定义动画
                .setLocatedCity(new LocatedCity(addressX, province, code))
                .setHotCities(hotCities)    //指定热门城市
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        if (data.getName() != null) {
                            EventBus.getDefault().post(data.getName(), "tag_refresh");
                        }
                    }

                    @Override
                    public void onLocate() {
                        //开始定位，这里模拟一下定位
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //定位完成之后更新数据
                                CityPicker.getInstance()
                                        .locateComplete(new LocatedCity(addressX, province, code), LocateState.SUCCESS);
                            }
                        }, 2000);
                    }
                })
                .show();
    }


    @Subscriber(tag = "tag_refresh")
    public void RefreshCity(String str) {
        address = str;
        tvAddress.setText(address);
        GetNowWeather();
        GetThreeDayWeather();
        GetSunupEnd();

    }

    /**
     * 获取实时天气天气
     */
    private void GetNowWeather() {
        loadingDialog.LoadingShow();
        //高德定位
        OkHttpUtils.get()
                .url(Constant.WEATHER_NOW + "location=" + address + "&key=" + Constant.FhKey + "&unit=i").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

                loadingDialog.LoadingDismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.e(response);
                WeatherNowBean weatherNowBean = JSON.parseObject(response, WeatherNowBean.class);
                List<WeatherNowBean.HeWeather6Bean> heWeather6 = weatherNowBean.getHeWeather6();
                if (heWeather6 != null) {
                    WeatherNowBean.HeWeather6Bean.NowBean now = heWeather6.get(0).getNow();
                    String cond_txt = now.getCond_txt();  //天气情况
                    String fl = now.getFl(); //温度
                    String cond_code = now.getCond_code();
                    DecimalFormat df = new DecimalFormat("#########.#");
                    String s = df.format((Float.parseFloat(fl) - 32) / 1.8);
                    tvTemperature.setText(s);
                    tvContext.setText(cond_txt);
                    if (cond_code.equals("100")) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.bg_share_fine);
                        llBg.setBackground(drawable);
                    } else if (cond_code.equals("101") || cond_code.equals("102") || cond_code.equals("103")) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.bg_share_cloudy);
                        llBg.setBackground(drawable);
                    } else if (cond_code.equals("104")) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.bg_share_fog);
                        llBg.setBackground(drawable);
                    } else if (cond_code.equals("300") || cond_code.equals("301") || cond_code.equals("305") || cond_code.equals("306") || cond_code.equals("399") || cond_code.equals("314") || cond_code.equals("309")) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.bg_share_rain);
                        llBg.setBackground(drawable);
                    } else if (cond_code.equals("302") || cond_code.equals("303") || cond_code.equals("304") || cond_code.equals("318") || cond_code.equals("317") || cond_code.equals("316") || cond_code.equals("315") || cond_code.equals("312") || cond_code.equals("311") || cond_code.equals("310") || cond_code.equals("318") || cond_code.equals("308") || cond_code.equals("307")) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.bg_share_overcast);
                        llBg.setBackground(drawable);
                    } else if (cond_code.equals("400") || cond_code.equals("401") || cond_code.equals("402") || cond_code.equals("408") || cond_code.equals("409") || cond_code.equals("410") || cond_code.equals("407") || cond_code.equals("499")) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.bg_share_snow);
                        llBg.setBackground(drawable);
                    } else if (cond_code.equals("503") || cond_code.equals("504") || cond_code.equals("507") || cond_code.equals("508")) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.bg_share_sand_storm);
                        llBg.setBackground(drawable);
                    } else if (cond_code.equals("509") || cond_code.equals("510") || cond_code.equals("511") || cond_code.equals("512") || cond_code.equals("513") || cond_code.equals("514") || cond_code.equals("515")) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.bg_share_haze);
                        llBg.setBackground(drawable);
                    }
                    tvWind.setText(now.getWind_dir());
                    tvGrade.setText(now.getWind_sc() + "级");
                    tvTemperatureX.setText(s + "℃");
                    tvAir.setText(now.getPres() + "mb");
                    tvHumidity.setText(now.getHum() + "%");
                    loadingDialog.LoadingDismiss();


                }
                loadingDialog.LoadingDismiss();

            }
        });

    }

    /**
     * 获取3天的天气
     */
    private void GetThreeDayWeather() {
        OkHttpUtils.get()
                .url(Constant.WEATHER_DAY + "location=" + address + "&key=" + Constant.FhKey + "&unit=i").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.e(response);
                WeatherDayBean weatherDayBean = JSON.parseObject(response, WeatherDayBean.class);
                WeatherDayBean.HeWeather6Bean heWeather6Bean = weatherDayBean.getHeWeather6().get(0);
                List<WeatherDayBean.HeWeather6Bean.DailyForecastBean> daily_forecast = heWeather6Bean.getDaily_forecast();
                if (daily_forecast != null) {
                    WeatherDayAdapter adapter = new WeatherDayAdapter(WeatherActivity.this, daily_forecast);
                    rcList.setAdapter(adapter);

                }
            }
        });

    }

    /**
     * 获取日出日落
     */
    private void GetSunupEnd() {
        OkHttpUtils.get()
                .url(Constant.SUNRISE + "location=" + address + "&key=" + Constant.FhKey + "&unit=i").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.e(response);
                WeatherSunupBean bean = JSON.parseObject(response, WeatherSunupBean.class);
                List<WeatherSunupBean.HeWeather6Bean> heWeather6 = bean.getHeWeather6();
                List<WeatherSunupBean.HeWeather6Bean.SunriseSunsetBean> sunrise_sunset = heWeather6.get(0).getSunrise_sunset();
                if (sunrise_sunset != null) {
                    String sr = sunrise_sunset.get(0).getSr();//日出
                    String ss = sunrise_sunset.get(0).getSs();//日落
                    int srH = Integer.parseInt(sr.split(":")[0]);
                    int srM = Integer.parseInt(sr.split(":")[1]);
                    int ssH = Integer.parseInt(ss.split(":")[0]);
                    int ssM = Integer.parseInt(ss.split(":")[1]);
                    // 设置日出时间
                    sv.setSunrise(srH, srM);
                    // 设置日落时间
                    sv.setSunset(ssH, ssM);
                    // 获取系统 时 分
                    Calendar calendar = Calendar.getInstance();
                    int hour = calendar.get(Calendar.HOUR_OF_DAY);
                    int minute = calendar.get(Calendar.MINUTE);
                    // 设置当前时间
                    sv.setCurrentTime(hour, minute);
                    GetLifeNum();
                }
            }
        });

    }

    /**
     * 获取生活指数
     */
    private void GetLifeNum() {
        OkHttpUtils.get()
                .url(Constant.LIFESTYLE + "location=" + address + "&key=" + Constant.FhKey + "&unit=i").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.e(response);
                WeatherLifeBean bean = JSON.parseObject(response, WeatherLifeBean.class);
                List<WeatherLifeBean.HeWeather6Bean.LifestyleBean> lifestyle = bean.getHeWeather6().get(0).getLifestyle();
                if (lifestyle != null) {
                    String brf = lifestyle.get(0).getBrf();
                    String txt = lifestyle.get(0).getTxt();
                    tvLifeNum.setText(brf);
                    tvLifeContext.setText(txt);
                }
            }
        });

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @OnClick({R.id.ll_select_address, R.id.iv_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_address:
                CityList();
                break;
            case R.id.iv_more:
                Uri uriX = Uri.parse("http://www.weather.com.cn/forecast/");
                Intent intentX = new Intent(Intent.ACTION_VIEW, uriX);
                startActivity(intentX);
                break;
        }
    }
}
